package org.example.service.imp;

import org.example.service.RedisService;
import org.example.util.HutoolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class RedisServiceImp implements RedisService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HutoolUtil hutoolUtil;
    @Override
    public long searchUniqueVisitorCount(String dateKye) {
        if (hutoolUtil.stringIsEmpty(dateKye)) return 0;
        Long size = redisTemplate.opsForHyperLogLog().size(dateKye);

        return size;
    }

    @Override
    public long searchDailyActiveUserCount(String dateKye) {
        if (hutoolUtil.stringIsEmpty(dateKye)) return 0;
        Long count = (Long) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                Long count = redisConnection.bitCount(dateKye.getBytes(StandardCharsets.UTF_8));
                return count;
            }
        });
        return count;
    }

    @Override
    public long searchUniqueVisitorCount(List<String> dateKeys) {
        if (dateKeys==null || dateKeys.size() == 0) return 0;
        String newKey = dateKeys.get(0) +"-"+dateKeys.get(dateKeys.size()-1);
        String[] temp = new String[dateKeys.size()];
        dateKeys.toArray(temp);
        redisTemplate.opsForHyperLogLog().union(newKey,temp);
        Long size = redisTemplate.opsForHyperLogLog().size(newKey);
        return size;
    }

    @Override
    public long searchDailyActiveUserCount(List<String> dateKeys) {
        //利用redis 中 bitmap类型 就是字符串(特殊的)
        if (dateKeys==null || dateKeys.size() == 0) return 0;
        long totalCount = 0;
        for (int i = 0;i<dateKeys.size();i++){
            String s = dateKeys.get(i);
            long count = searchDailyActiveUserCount(s);
            totalCount += count;
        }

        return totalCount;
    }

    @Override
    public int saveUniqueVisitorUser(String dateKey, String ip) {
        if (hutoolUtil.stringIsEmpty(dateKey) || hutoolUtil.stringIsEmpty(ip)) return 0;
        redisTemplate.opsForHyperLogLog().add(dateKey,ip);
        return 1;
    }

    @Override
    public int saveDailyActiveUser(String dateKey, long id) {
        if (hutoolUtil.stringIsEmpty(dateKey) || id<=0) return 0;
        redisTemplate.opsForValue().setBit(dateKey,id,true);
        return 1;
    }
}
